package cn.fastoo.web.api.controller.sys;

import cn.fastoo.alipay.AlipayConfig;
import cn.fastoo.common.dao.*;
import cn.fastoo.common.entity.*;
import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.utils.BigDecimalUtil;
import cn.fastoo.common.utils.HttpClientHelper;
import cn.fastoo.utils.ConfigProps;
import cn.fastoo.utils.HttpRequestUtils;
import cn.fastoo.web.api.controller.user.RechargeController;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.ConnectException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by hp on 2017/7/28.
 */
@Controller
@RequestMapping("/v1/sys")
public class SystemController {

    private final Logger logger = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    private CountryDictDao countryDictDao;
    @Autowired
    private RechargeDao rechargeDao;
    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private UserBalanceRemindDao userBalanceRemindDao;


    @RequestMapping("getQuotedPrice")
    @ResponseBody
    public String getQuotedPrice(@RequestParam String country){
        CountryDict countryDict = countryDictDao.findOne(new Search().addSearchFilter("EQ_nameEn",country));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mtprice","未知");
        jsonObject.put("vtprice","未知");
        if (countryDict!=null) {
            jsonObject.put("mtprice",countryDict.getMtprice());
            jsonObject.put("vtprice",countryDict.getVtprice());
        }
        return new JsonResult(0,"ok",jsonObject).toJson();
    }

    @RequestMapping({"updateStatus"})
    public void updateOrderStatus(HttpServletRequest request) throws Exception {

        //商户订单号
        String rechargeNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //付款金额
        String totalAmount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
        String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");

        if ("get".equals(request.getMethod())) {
            logger.info("同步进入updateStatus更新订单状态：rechargeNo=" + rechargeNo + ",tradeNo=" + tradeNo + ",totalAmount=" + totalAmount + ",totalAmount=" + totalAmount + ",subject=" + subject);
        } else {
            logger.info("异步进入updateStatus更新订单状态：rechargeNo=" + rechargeNo +",tradeNo=" + tradeNo+ ",totalAmount=" + totalAmount + ",totalAmount=" + totalAmount + ",subject=" + subject);
        }

        //推送参数
        String param = "";


        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }

            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            logger.info("验证成功");
            Double totalPrice = Double.valueOf(totalAmount);
            Recharge recharge = rechargeDao.findOne(new Search().addSearchFilter("EQ_rechargeNo",rechargeNo));
            if (recharge==null) {

            }
            if (recharge.getStatus() != 1) {
                UserBase userBase = userBaseDao.findById(recharge.getUserBaseId());
                Double balance = userBase.getBalance();
                logger.info("用户loginName = " + userBase.getLoginName() + ",当前金额 balance is " + balance);


                /******************** 更新用户金额 **************************/
                balance = BigDecimalUtil.add(balance, totalPrice);

                logger.info("用户loginName = " + userBase.getLoginName() + ",充值后金额 balance is " + balance);

                /************ 更新订单 *************/
                recharge.setBalance(balance);
                recharge.setTradeNo(tradeNo);
                recharge.setStatus(1);
                recharge.setCreateTime(new Date());
                rechargeDao.update(recharge);


                /********** 更新账户 ********/
                userBase.setBalance(balance);
                userBaseDao.update(userBase);

                /****更新余额提醒实体****/
                UserBalanceRemind remind = userBalanceRemindDao.findOne(new Search().addSearchFilter("EQ_userBaseId",userBase.getId()));
                if (remind!=null) {
                    remind.setLastChargeTime(new Date());
                    userBalanceRemindDao.update(remind);
                }


            }
            //结果推送给NODEJS
            param = "?result=1";
            send(ConfigProps.getNodejsUrl()+param);
        }else {
            param = "?result=0";
            send(ConfigProps.getNodejsUrl()+param);
        }
    }


    public void send(String url) throws Exception {
        long ts = (new Date()).getTime();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = HttpClientHelper.getHttpClient().execute(httpGet);

        try {
            HttpEntity entity = httpResponse.getEntity();
            int statusCode = httpResponse.getStatusLine().getStatusCode();
//            String res = EntityUtils.toString(entity);
            EntityUtils.consume(entity);//销毁
            if (statusCode > 400) {
                // 单条请求出错抛出异常
                throw new ConnectException("Connection Error. " + statusCode + "," + url);
            } else {
                logger.info(statusCode + ":" + ((new Date()).getTime() - ts ) + "ms:" + url);
            }
        } finally {
            httpResponse.close();
        }
    }

}
